<template>
	<view class="test-page">
		<view class="name">{{content.title}}</view>
		<scroll-view  scroll-y="true" class="scroll-Y" >
			<view class="select-item" v-for="(item,index) in list">
				<view class="top">
					<span class="index">{{active+1}}</span>
					<span class="text" v-html="item.content"></span>
					<span class="type" v-show="item.examType=='1'">单选</span>
					<span class="type" v-show="item.examType=='2'">多选</span>
					<span class="type" v-show="item.examType=='3'">填空</span>
					<span class="type" v-show="item.examType=='4'">判断</span>
					<span class="type" v-show="item.examType=='5'">简答</span>
					<view style="clear:both"></view>
				</view>
				<view class="radio-box" v-show="item.examType=='1' || item.examType=='4'">
					<radio-group @change="radioChange($event,index)" >
						<view class="main-data">
							<span class="item" v-for="(item1, index1) in item.educationExamOptionList" :key="index1">
								<radio :value="item1.label" :checked="item.answer === item1.label" color="#1783dd" style="transform: scale(0.9)"/>
								<span class="text">{{item1.label}}</span>
								<span class="text" style="color:#1783dd">{{item1.content}}</span>
							</span>
						</view>		
					</radio-group>
				</view>
				<view class="radio-box" v-show="item.examType=='2'">
					<checkbox-group @change="checkboxChange($event,index)">
						<view class="main-data">
							<span class="item" v-for="(item1, index1) in item.educationExamOptionList" :key="index1">
								<checkbox v-if="isShowChecked" :value="item1.label" :checked="item1.checked" color="#1783dd"/>
								<span class="text">{{item1.label}}</span>
								<span class="text" style="color:#1783dd">{{item1.content}}</span>
							</span>
						</view>
					</checkbox-group>
				</view>
				<view class="radio-box" v-show="item.examType=='3'|| item.examType=='5'">
					<textarea v-model="item.answer" :auto-height="true" class="main-textarea" placeholder="请输入答案" maxlength="-1"></textarea>
				</view>
			</view>
			<view class="button-box" :class="active==0?'flex-new':''">
				<!-- <view class="pre" v-show="active!=0" @tap="pre">上一题</view> -->
				<view class="next" v-show="(active+1)<all.length" @tap="next">下一题</view>
				<view class="next" v-show="(active+1)==all.length" @tap="submitGo">提交</view>
			</view>
		</scroll-view>
		
		<!-- <view class="submit" @tap="submit">提交问卷</view> -->
		<view class="backhome iconfont iconshouye-yes" @tap="$gohome"></view>
	</view>
</template>

<script>
	import Cookies from 'js-cookie'
	export default {
		components:{
			
		},
		data() {
			return {
				isShowChecked:true,
				time:"",
				all:[
				],
				active:0,
				list:[],
				content:{},
				userPaperId:'',
				classId:'',
				classCourseId:'',
				timeDate:0,
				id:'',
				curStartTime:'',
				allTime:'',
				id1:'',
				paperData:{},
				timer:null,
			}
		},
		onLoad(options) {
			this.id = options.id;
			uni.showLoading();
			this.getId();
			// this.paperData = JSON.parse(uni.getStorageSync("paperData"));
			
		},
		onUnload() {
			if(this.timer) {  
				clearTimeout(this.timer);  
				this.timer = null;  
			}  
		},
		onHide() {
			if(this.timer) {
				clearTimeout(this.timer);  
				this.timer = null;  
			}  
		},
		
		methods: {
			goCenter(item){
				uni.navigateTo({
					url:'main'
				})
			},
			getContent(id){
				let that = this;
				this.$http.get("/f/exam/findUserAnswerByExamId?userPaperId="+this.userPaperId+"&examId="+id)
	            .then(function (response) {
	                let list = response.data;
	                if(list.length!=0){
	                	that.list[0].answer = list[0].userAnswer;
	                	if(that.list[0].examType=="3"){
	                		let arr = that.list[0].answer.split("|");
	                		that.list[0].options.forEach((item,i)=>{
	                			arr.forEach((item1,i1)=>{
	                				if(item.labels==item1){
	                					console.log(item1)
	                					item.checked = true;
	                				}
	                			})
	                		})
	                		console.log(that.list);
	                	}
	                }
	            })
	            .catch(function (error) {
	                // handle error
	                console.log(error);
	            })
			},
			formatDate(date){
		        date = new Date(date);
		        var y=date.getFullYear();
		        var m=date.getMonth()+1;
		        var d=date.getDate();
		        var h=date.getHours();
		        var m1=date.getMinutes();
		        var s=date.getSeconds();
		        m = m<10?("0"+m):m;
		        m1 = m1<10?("0"+m1):m1;
		        d = d<10?("0"+d):d;
		        return y+"-"+m+"-"+d+" "+h+":"+m1+":"+s;
		    },
		    countTime () {
		      // 获取当前时间
		      let date = new Date()
		      let now = date.getTime()
		      // 设置截止时间
		      let endDate = new Date(this.curStartTime) // this.curStartTime需要倒计时的日期
		      let end = endDate.getTime()
		      // 时间差
		      let leftTime = end - now
		      // 定义变量 d,h,m,s保存倒计时的时间
		      if (leftTime >= 0) {
		        // 天
		        this.day = Math.floor(leftTime / 1000 / 60 / 60 / 24)
		        // 时
		        let h = Math.floor(leftTime / 1000 / 60 / 60 % 24)
		        this.hour = h < 10 ? '0' + h : h
		        // 分
		        let m = Math.floor(leftTime / 1000 / 60 % 60)
		        this.min = m < 10 ? '0' + m : m
		        // 秒
		        let s = Math.floor(leftTime / 1000 % 60)
		        this.second = s < 10 ? '0' + s : s
		      } else {
		        this.day = 0
		        this.hour = '00'
		        this.min = '00'
		        this.second = '00'
		        
		            
		          
		      }
		      // 等于0的时候不调用
		      if (Number(this.hour) === 0 && Number(this.day) === 0 && Number(this.min) === 0 && Number(this.second) === 0) {
		        // this.$confirm('本堂测试已结束,请点击确认按钮查看测试结果', '提示', {
		        //   confirmButtonText: '确定',
		        //   cancelButtonText: '取消',
		        //   showCancelButton:false,
		        //   closeOnClickModal:false,
		        //   showClose:false,
		        //   type: 'warning'
		        // }).then(() => {
		        //   this.$router.push("/result/"+this.id);
		        // }).catch(() => {
		                    
		        // });
				uni.showModal({
				    title: '提示',
				    content: '本堂测试已结束,请点击确认按钮查看测试结果',
				    success: function (res) {
				        if (res.confirm) {
							// this.$router.push("/result/"+this.id);
							setTimeout(()=>{
								uni.navigateTo({
									url:'../course/result?id='+this.id
								})
							},500)
				            console.log('用户点击确定');
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});
		      } else {
		      // 递归每秒调用countTime方法，显示动态时间效果,
		        this.timer = setTimeout(() => {
		          this.timeDate = this.timeDate+1;
		          
		          //console.log(this.timeDate)
		          this.countTime(this.curStartTime);
		        },1000)
		      }
		    },
		    getTicontent(data,i){
		    	let that = this;
				this.$http.get("/f/examById?id="+data[i].id)
	            .then(function (response) {
	            	data[i] = Object.assign(data[i],response.data)
	            	if(data.length==(i+1)){
	            		data.forEach((item,i)=>{
	                		item.answer = "";
	                		item.educationExamOptionList.forEach((item1,i1)=>{
								
	                			item1.checked = false;
								// item1.checked = null;
	                		})
	                	})

	                	that.all = data;
		                let arr = [];
						let obj = that.all[that.active];
						arr.push(obj);
						that.list = arr;
	            	}
	                
	                uni.hideLoading();
	            })
	            .catch(function (error) {
	                // handle error
	                console.log(error);
	            })
		    },
		    getList(){
		    	let that = this;
				this.$http.get("/f/examByPaperId?id="+this.id1+"&paperId="+this.id)
	            .then(function (response) {
	            	console.log(response,99)
	                //that.userPaperId = response.data.userPaper.userPaperId;
	                let list = response.data;
	                if(list.length!=0){
	                	list.forEach((item,i)=>{
	                		that.getTicontent(list,i)
	                	})
	                }
	                
	                uni.hideLoading();
	            })
	            .catch(function (error) {
	                // handle error
	                console.log(error);
	            })
		    },
			getId(){
				let that = this;
				this.$http.get("/f/startUserPaper?paperId="+this.id)
	            .then(function (response) {
	                   that.content = response.data.educationPaper;
	                   that.id1 = response.data.id;
			          var now = new Date();
			          var time = now.getTime() + response.data.educationPaper.testTimeSecond*1000;
			          that.allTime = response.data.educationPaper.testTimeSecond;
			          var a = that.formatDate(time);
			          that.curStartTime = a;
					  let testTimeSecond = response.data.educationPaper.testTimeSecond
					  //如果试卷设置了测试时长，则需要在页面加上测试时长判断，时间到了，则进入到查看成绩页面
					  if(testTimeSecond){
						that.countTime(a);
					  }
			          that.getList();
	                
	                uni.hideLoading();
	            })
	            .catch(function (error) {
	                // handle error
	                console.log(error);
	            })
			},
			radioChange(e,index){
				this.list[index].answer = e.detail.value;
				console.log(e)
			},
			checkboxChange(e,index){
				this.list[index].answer = e.detail.value.join(",");
			},
			pre(){
				
				this.active = this.active - 1;
				let arr = [];
				let obj = this.all[this.active];
				arr.push(obj);

				this.list = arr;
				this.getContent(this.list[0].id);
			},
			next(){
				this.submit(this.list[0].id,this.list[0].answer,false)
				this.isShowChecked = false;
				this.$nextTick(()=>{
					this.isShowChecked = true;
				})
				// this.all.forEach((item,i)=>{
				// 	item.answer = "";
				// 	item.educationExamOptionList.forEach((item1,i1)=>{
				// 		this.$set(item1,'checked',false)
				// 		// item1.checked = false;
				// 		console.log(item1,9999)
				// 	})
				// })

			},
			submitGo(){
				this.submit(this.list[0].id,this.list[0].answer,true)
			},
			submit(id,answer,type){
				let that = this;
				let obj = {
					userPaperId:this.userPaperId,
					examId:id,
					userAnswer:answer
				}
				let url = "";
				if(type){
					uni.showLoading({
						title:'试卷提交中...',
						mask:true
					})
					url = "/f/saveExamRecord?examId="+id+"&remainTime="+this.timeDate+"&submitPaper="+type+"&userAnswer="+answer+"&userPaperId="+this.id1+"&paperId="+this.id;
				}
				else{
					url = "/f/saveExamRecord?examId="+id+"&remainTime="+this.timeDate+"&submitPaper="+type+"&userAnswer="+answer+"&userPaperId="+this.id1+"&paperId="+this.id;
				}
				this.$http.post(url)
	            .then(function (response) {
	            	if(!type){
	            		that.active = that.active + 1;
						let arr = [];
						let obj = that.all[that.active];
						arr.push(obj);

						that.list = arr;
						//that.getContent(that.list[0].id);
	            	}
	            	else{
	            		uni.showToast({
							title:'您的试卷已提交',
						})
						setTimeout(()=>{
							uni.navigateTo({
								url:'../course/result?id='+that.id1
							})
						},500)
	            		
	            	}
	                
	            })
	            .catch(function (error) {
	                // handle error
	                console.log(error);
	            })
				
			},
			upTest(id){
				let that = this;
				this.$http.post("/f/exam/jiaojuanpaper?userPaperId="+id)
	            .then(function (response) {
	            	uni.hideLoading();
            		uni.showToast({
						title:'您的测试已提交',
						iconfont:'success'
					})
					setTimeout(()=>{
						that.back();
					},500)
	                
	            })
	            .catch(function (error) {
	                // handle error
	                console.log(error);
	            })
			},
			back(){
				uni.navigateBack({
				    delta: 1
				});
			},
			back(){
				uni.navigateBack({
				    delta: 1
				});
			},
			startTime() {
			    var today = new Date();
			    var h = today.getHours();
			    var m = today.getMinutes();
			    var s = today.getSeconds();
			    // 在 numbers<10 的数字前加上 0
			    m = this.checkTime(m);
			    s = this.checkTime(s);
			    this.time = h + ":" + m + ":" + s;
			    setTimeout(()=>{
			    	this.startTime();
			    },1000)
			    
			},
			checkTime(i) {
			    if (i < 10) {
			        i = "0" + i;
			    }
			    return i;
			},
			datechange(e){
				console.log(e)
			}
		}
	}
</script>

<style lang="less">
	.test-page{
		width:100%;
		height:100%;
		position:relative;
		background:#f5f5f5;
		.button-box{
			width:600rpx;
			display:flex;
			margin:50rpx auto;
			justify-content:center;
			.pre{
				width:280rpx;
				height:80rpx;
				border-radius:40rpx;
				text-align:center;
				line-height:80rpx;
				font-size:32rpx;
				color:#fff;
				background:#5db2f5;
			}
			.next{
				width:280rpx;
				height:80rpx;
				border-radius:40rpx;
				text-align:center;
				line-height:80rpx;
				font-size:32rpx;
				color:#fff;
				background:#1783dd;
			}
		}
		.flex-new{
			justify-content:center;
		}
		.submit{
			position:absolute;
			bottom:40rpx;
			width:280rpx;
			height:70rpx;
			line-height:70rpx;
			text-align:center;
			font-size:30rpx;
			color:#ffffff;
			border-radius:10rpx;
			background:#1783dd;
			left:235rpx;
			z-index: 99;
		}
		.scroll-Y{
			width:100%;
			// height:calc(100% - 90rpx);
			float:left;

		}
		.select-item{
			width:calc(100% - 40rpx);
			box-sizing:border-box;
			margin:0 auto;
			margin-top:40rpx;
			background:#ffffff;
			padding:20rpx 30rpx;
			border-radius:10rpx;
			.radio-box{
				width:100%;
				margin:40rpx 0;
				margin-bottom:0rpx;
				.main-textarea{
					width:calc(100% - 40rpx);
					line-height:40rpx;
					display:flex;
					min-height:120rpx;
					background:#f5f5f5;
					font-size:28rpx;
					color:#888888;
					padding: 20rpx;
					margin-bottom:20rpx;
				}
				.main-data{
					width:100%;
					display:flex;
					flex-wrap:wrap;
					.item{
						margin-right:30rpx;
						display:flex;
						align-items:center;
						margin-bottom:30rpx;
						.text{
							font-size:30rpx;
							color:#666666;
							margin-left:10rpx;
						}
					}
				}
				.uni-list-cell{
					width:auto;
				}
			}
			.top{
				width:100%;
				position:relative;
				.type{
					line-height:60rpx;
					right:0;
					font-size:30rpx;
					color:#1783dd;
					position:absolute;
					top:0;
				}
				.index{
					width:60rpx;
					height:60rpx;
					border-radius:50%;
					background:#1783dd;
					line-height:60rpx;
					text-align:center;
					font-size:28rpx;
					color:#fff;
					margin-right:20rpx;
					float:left;
				}
				.text{
					font-size:32rpx;
					color:#555555;
					float:left;
					width:calc(100% - 160rpx);
					display:block;
					line-height:40rpx;
					margin-top:10rpx;
					word-break: break-all;
				}
			}
		}
		.select-item:last-child{
			margin-bottom:120rpx;
		}
		float:left;
		.name{
			display:block;
			text-align:center;
			line-height:60rpx;
			font-size:36rpx;
			color:#444444;
			margin-top:30rpx;
		}
	}
</style>
